package com.msf.smile.controller;

import com.msf.smile.entity.User;
import com.msf.smile.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("/test")
public class HelloWorldController {

    @Resource
    UserService userService;

    @RequestMapping("/index.html")
    public String say(Model model) {
        model.addAttribute("name", "hello, world");
        return "/index.btl";
    }

    @RequestMapping("/index.json")
    public @ResponseBody String say() {
        return "hello, world";
    }

    @RequestMapping(value="/get/{id}.json")
    public @ResponseBody User getById(@PathVariable("id") Long id) {
        return userService.getUserById(id);
    }

    @RequestMapping(value="/consumes/test.json", consumes = "application/json")
    @ResponseBody
    public User forJson() {
        return userService.getUserById(1L);
    }

    @GetMapping(value="/user/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public User getUser(@PathVariable Long userId, Model model) {
        return userService.getUserById(userId);
    }

    @PostMapping(path = "/update.json", params = "action=save")
    @ResponseBody
    public void saveUser() {
        System.out.println("call save");
    }

    @PostMapping(path = "/update.json", params = "action=update")
    @ResponseBody
    public void updateUser() {
        System.out.println("call update");
    }

    @GetMapping(path = "/update.json", headers = "action=update")
    @ResponseBody
    public void updateGetUser() {
        System.out.println("call updateGet");
    }

    @PostMapping(path = "/savejsonorder.json")
    public @ResponseBody String saveOrderByJson(@RequestBody User user) {
        System.out.println(user.getName());
        return user.getName();
    }

    @PostMapping("/form")
    public @ResponseBody String handleFormUpload(String name, MultipartFile file)
            throws IOException {
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            InputStream ins = file.getInputStream();

            // 处理上传内容
            return "success";
        }
        return "failure";
    }
}
